<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>新增设备</span>
        <el-button type="primary" @click="goBack" plain>返回列表</el-button>
      </div>
    </template>
    
    <el-form 
      ref="formRef" 
      :model="form" 
      :rules="rules" 
      label-width="100px"
      label-position="top"
      style="max-width: 600px;"
    >
      <el-form-item label="区域" prop="areaId">
        <el-cascader
          v-model="form.areaId"
          :options="hierarchyOptions"
          :props="hierarchyProps"
          clearable
          :placeholder="loading ? '正在加载数据...' : hierarchyOptions.length === 0 ? '暂无数据，请先添加客户、站点和区域' : '请选择客户 -> 站点 -> 区域'"
          style="width: 100%;"
          filterable
          :show-all-levels="true"
          :separator="' / '"
          collapse-tags
          collapse-tags-tooltip
          :loading="loading"
        />
        <div v-if="loading" class="loading-tip">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>正在加载层级数据...</span>
        </div>
        <div v-if="!loading && hierarchyOptions.length === 0" class="empty-tip">
          <el-icon><Warning /></el-icon>
          <span>暂无层级数据，请先添加客户、站点和区域</span>
        </div>
      </el-form-item>
      
      <el-form-item label="设备型号" prop="model">
        <el-input 
          v-model="form.model" 
          placeholder="请输入设备型号" 
          clearable
        />
      </el-form-item>
      
      <el-form-item label="序列号" prop="serialNo">
        <el-input 
          v-model="form.serialNo" 
          placeholder="请输入设备出厂序列号" 
          clearable
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Loading, Warning } from '@element-plus/icons-vue';
import DeviceAPI from '@/api/system/device.api';
import SiteAPI from '@/api/system/site.api';
import CustomerAPI from '@/api/system/customer.api';

const router = useRouter();

const formRef = ref(null);
const form = reactive({
  areaId: null,
  model: '',
  serialNo: '',
});

const rules = reactive({
  areaId: [
    { required: true, message: '请选择区域', trigger: 'change' },
    { 
      validator: (rule, value, callback) => {
        if (value && value.length < 3) {
          callback(new Error('请选择完整的客户 -> 站点 -> 区域路径'));
        } else {
          callback();
        }
      }, 
      trigger: 'change' 
    }
  ],
  model: [{ required: true, message: '请输入设备型号', trigger: 'blur' }],
  serialNo: [{ required: true, message: '请输入序列号', trigger: 'blur' }],
});

const hierarchyOptions = ref([]);
const loading = ref(false);
const hierarchyProps = {
  label: 'name',
  value: 'id',
  children: 'children',
  checkStrictly: true,
  multiple: false,
};

// 加载完整的层级数据
const loadHierarchyOptions = async () => {
  loading.value = true;
  try {
        const res = await SiteAPI.getFullHierarchy();
    
    // request工具已经处理了响应，直接返回data部分
    if (res && Array.isArray(res)) {
        
        // 修复层级结构（临时解决方案）
        const fixHierarchy = (data) => {
          return data.map(customer => {
            const fixedCustomer = { ...customer };
            if (customer.children) {
              fixedCustomer.children = customer.children.map(site => {
                const fixedSite = { ...site };
                if (site.children) {
                  // 重新构建区域层级
                  const areaMap = new Map();
                  const rootAreas = [];
                  
                  // 创建所有区域节点
                  site.children.forEach(area => {
                    areaMap.set(area.id, { ...area, children: [] });
                  });
                  
                  // 构建父子关系 - 基于名称匹配（临时解决方案）
                  site.children.forEach(area => {
                    // 如果后端没有提供parentAreaId，尝试基于名称匹配
                    if (!area.parentAreaId || area.parentAreaId === undefined || area.parentAreaId === 0 || area.parentAreaId === '0') {
                      // 检查是否是楼层（包含"层"字）
                      if (area.name.includes('层')) {
                        // 查找可能的父级建筑（包含"栋"字）
                        const possibleParent = site.children.find(a => 
                          a.name.includes('栋') && a.id !== area.id
                        );
                        if (possibleParent) {
                          const parent = areaMap.get(possibleParent.id);
                          if (parent) {
                            parent.children.push(areaMap.get(area.id));
                          } else {
                            rootAreas.push(areaMap.get(area.id));
                          }
                        } else {
                          rootAreas.push(areaMap.get(area.id));
                        }
                      } else {
                        rootAreas.push(areaMap.get(area.id));
                      }
                    } else {
                      // 使用后端提供的parentAreaId
                      const parent = areaMap.get(area.parentAreaId);
                      if (parent) {
                        parent.children.push(areaMap.get(area.id));
                      } else {
                        rootAreas.push(areaMap.get(area.id));
                      }
                    }
                  });
                  
                  fixedSite.children = rootAreas;
                }
                return fixedSite;
              });
            }
            return fixedCustomer;
          });
        };
        
        const fixedData = fixHierarchy(res);
        hierarchyOptions.value = fixedData || [];
      } else {
        console.warn('层级数据为空或格式不正确:', res);
        hierarchyOptions.value = [];
      }
  } catch (error) {
    ElMessage.error('加载层级数据失败');
    console.error('加载层级数据失败:', error);
    console.error('错误详情:', error.response || error);
    hierarchyOptions.value = [];
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate();
    
    // 验证是否选择了完整的层级路径
    if (!form.areaId || form.areaId.length < 3) {
      ElMessage.error('请选择完整的客户 -> 站点 -> 区域路径');
      return;
    }
    
    // 获取最后一级（区域）的ID
    const areaId = form.areaId[form.areaId.length - 1];
    
    await DeviceAPI.create({ 
      ...form, 
      areaId 
    });
    
    ElMessage.success('新增设备成功');
    goBack();
  } catch (error) {
    console.error('新增设备失败:', error);
    ElMessage.error(error.message || '新增设备失败');
  }
};

// 重置表单
const resetForm = () => {
  formRef.value.resetFields();
};

// 返回列表
const goBack = () => {
  router.push({ name: 'deviceList' });
};

onMounted(() => {
  loadHierarchyOptions();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 级联选择器样式优化 */
:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-cascader__tags) {
  flex-wrap: wrap;
}

:deep(.el-cascader__collapse-tags) {
  display: flex;
  align-items: center;
}

/* 加载状态样式 */
:deep(.el-cascader.is-loading .el-cascader__label) {
  color: #c0c4cc;
}

.loading-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

.loading-tip .el-icon {
  font-size: 14px;
}

.empty-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  color: #e6a23c;
  font-size: 12px;
}

.empty-tip .el-icon {
  font-size: 14px;
}
</style>